package cre.tomcat.ch06.startup;

import cre.tomcat.ch06.core.*;
import org.apache.catalina.Container;
import org.apache.catalina.Loader;
import org.apache.catalina.connector.http.HttpConnector;

/**
 * tomcat bootstrap
 *
 * @Author penglai
 * @Date 2017/1/4.
 */
public class Bootstrap {

    public static void main(String[] args) {
        HttpConnector connector = new HttpConnector();
        Container container = createContainer();
        try {
            connector.setContainer(container);
            connector.initialize();

            connector.start();
            ((SimpleContext)container).start();

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Container createContainer() {
        SimpleWrapper wrapper1 = new SimpleWrapper();
        wrapper1.setName("Primitive");
        wrapper1.setServletClass("cre.tomcat.ch03.servlet.PrimitiveServlet");

        SimpleWrapper wrapper2 = new SimpleWrapper();
        wrapper2.setName("Modern");
        wrapper2.setServletClass("cre.tomcat.ch03.servlet.ModernServlet");

        SimpleContext container = new SimpleContext();
        container.addChild(wrapper1);
        container.addChild(wrapper2);
        container.addServletMapping("/Primitive", "Primitive");
        container.addServletMapping("/Modern", "Modern");

        Loader loader = new SimpleLoader();
        container.setLoader(loader);

        SimpleContextMapper mapper = new SimpleContextMapper();
        mapper.setProtocol("http");

        SimpleContextLifecycleListener lifecycleListener = new SimpleContextLifecycleListener();
        container.addLifecycleListener(lifecycleListener);

        container.addMapper(mapper);
        return container;
    }
}
